package com.two.screen.water.balance.ui.service

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.BatteryManager
import com.two.screen.water.balance.utils.CommUtils
import com.two.screen.water.balance.utils.UtilsBigDecimal
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import java.math.BigDecimal

/**
 * 创建者     Noel
 * 创建时间   2019/4/17 11:40
 */
class GetBatteryChangedReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            "android.intent.action.BATTERY_CHANGED" -> {
                var level = intent.getIntExtra("level", 0);    ///电池剩余电量
                var scale = intent.getIntExtra("scale", 0);  ///获取电池满电量数值
                var technology = intent.getStringExtra("technology");  ///获取电池技术支持
                var status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN); ///获取电池状态
                var plugged = intent.getIntExtra("plugged", 0);  ///获取电源信息
                var health = intent.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);  ///获取电池健康度
                var voltage = intent.getIntExtra("voltage", 0);  ///获取电池电压
                var temperature = intent.getIntExtra("temperature", 0);  ///获取电池温度

                var batteryStatus = when (status) {
                    BatteryManager.BATTERY_STATUS_CHARGING -> "充电中"
                    BatteryManager.BATTERY_STATUS_DISCHARGING -> "放电中"
                    BatteryManager.BATTERY_STATUS_FULL -> "已充满"
                    BatteryManager.BATTERY_STATUS_UNKNOWN -> "未知状态"
                    else -> "未知状态"
                }
                var num = try {
                    UtilsBigDecimal.div(level.toDouble(), scale.toDouble()).multiply(BigDecimal(100)).toInt()
                } catch (e: Exception) {
                    100
                }
                var msg = "battery:$num%,level:$level,scale:$scale,technology:$technology,batteryStatus:$batteryStatus,plugged:$plugged,health:$health,voltage:$voltage,temperature:$temperature"


                EventBusUtil.sendStickyEvent(Event(EventCode.BATTERY_CHANGED_DATA, BatteryChangedBean(num, status)))
                CommUtils.println("BATTERY_CHANGED->", msg)
            }
        }
    }
}

data class BatteryChangedBean(var num: Int = 0, var status: Int = 0)
